package edu.xmut.kakamusic.fragment.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.content.Context;
import android.content.DialogInterface;
import android.content.ClipboardManager;
import android.content.ClipData;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;

import java.util.Locale;
import java.util.Map;
import java.util.Objects;

import edu.xmut.kakamusic.MainActivity;
import edu.xmut.kakamusic.R;
import edu.xmut.kakamusic.bean.form.UserLoginForm;
import edu.xmut.kakamusic.databinding.FragmentLoginDetailBinding;
import edu.xmut.kakamusic.utils.ApiResponse;
import edu.xmut.kakamusic.utils.RequestUtils;
import edu.xmut.kakamusic.utils.SPUtils;
import edu.xmut.kakamusic.utils.SnackBarUtil;
import edu.xmut.kakamusic.utils.ToastUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;


public class LoginDetailFragment extends Fragment {


    private ConstraintLayout root;
    private FragmentLoginDetailBinding binding;
    private final String TAG = getClass().getSimpleName();
    private CountDownTimer countDownTimer;
    private static final int COUNTDOWN_TIME = 60000; // 60秒
    private static final int COUNT_DOWN_INTERVAL = 1000; // 1秒间隔

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentLoginDetailBinding.inflate(inflater, container, false);
        root = binding.getRoot();
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        binding.btnLoginConfirm.setOnClickListener(this::login);
        binding.btnGetCode.setOnClickListener(this::getVerifyCode);
        initCountDownTimer();
    }

    private void initCountDownTimer() {
        countDownTimer = new CountDownTimer(COUNTDOWN_TIME, COUNT_DOWN_INTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 更新按钮文本显示剩余秒数
                binding.btnGetCode.setText(String.format(Locale.getDefault(), "%ds后重新获取", millisUntilFinished / 1000));
                binding.btnGetCode.setEnabled(false);
            }

            @Override
            public void onFinish() {
                // 倒计时结束，恢复按钮状态
                binding.btnGetCode.setText("获取验证码");
                binding.btnGetCode.setEnabled(true);
            }
        };
    }

    private void getVerifyCode(View view) {
        String phone = Objects.requireNonNull(binding.tvLoginPhone.getText()).toString();
        if (phone.length() != 11) {
            SnackBarUtil.showSnackBar(requireActivity(), root, "请输入正确的手机号", true, 0, null);
            return;
        }
        // 调用获取验证码的API
        RequestUtils.getInstance().getCode(phone)
                .enqueue(new Callback<ApiResponse<Map<String, String>>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<Map<String, String>>> call, Response<ApiResponse<Map<String, String>>> response) {
                        if (response.isSuccessful()) {
                            ApiResponse<Map<String, String>> apiResponse = response.body();
                            if (Objects.nonNull(apiResponse) && Objects.equals(apiResponse.getCode(), 200)) {
                                Map<String, String> data = apiResponse.getData();
                                Log.d(TAG, "onResponse: " + data);
                                String code = data.get("code");
                                // 显示验证码弹窗
                                showVerifyCodeDialog(code);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<Map<String, String>>> call, Throwable t) {
                        SnackBarUtil.showSnackBar(requireActivity(), root, "网络错误" + t.getMessage(), true, 0, null);
                    }
                });
        // 开始倒计时
        countDownTimer.start();
        // 发送验证码成功提示
        SnackBarUtil.showSnackBar(requireActivity(), root, "验证码已发送", true, 0, null);
    }

    /**
     * 显示验证码弹窗
     */
    private void showVerifyCodeDialog(String code) {
        if (getActivity() == null) {
            return;
        }
        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(getActivity())
                .setTitle("验证码")
                .setMessage("您的验证码是：" + code)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton("复制", (dialog, which) -> {
                    // 复制验证码到剪贴板
                    ClipboardManager clipboard = (ClipboardManager)
                            requireActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("验证码", code);
                    clipboard.setPrimaryClip(clip);
                    SnackBarUtil.showSnackBar(requireActivity(), root, "验证码已复制到剪贴板", true, 0, null);
                })
                .setNegativeButton("关闭", (dialog, which) -> dialog.dismiss())
                .setCancelable(true);

        // 在主线程中显示对话框
        requireActivity().runOnUiThread(() -> {
            AlertDialog dialog = builder.create();
            dialog.show();

            // 设置按钮颜色
            dialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(
                    ContextCompat.getColor(requireContext(), R.color.main_color));
            dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(
                    ContextCompat.getColor(requireContext(), R.color.text_grey));
        });
    }

    private void login(View view) {
        String phone = Objects.requireNonNull(binding.tvLoginPhone.getText()).toString();
        String verifyCode = Objects.requireNonNull(binding.tvVerifyCode.getText()).toString();

        if (binding.cbLoginRead.isChecked()) {
            if (phone.isEmpty() || verifyCode.isEmpty()) {
                SnackBarUtil.showSnackBar(requireActivity(), root, "手机号或验证码不能为空", true, 0, null);
            } else if (phone.length() != 11) {
                SnackBarUtil.showSnackBar(requireActivity(), root, "请输入正确的手机号", true, 0, null);
            } else if (verifyCode.length() != 4) {
                SnackBarUtil.showSnackBar(requireActivity(), root, "请输入4位验证码", true, 0, null);
            } else {
                // 调用验证码登录的API
                UserLoginForm form = new UserLoginForm(phone, null, verifyCode);
                RequestUtils.getInstance().loginByCode(form)
                        .enqueue(new Callback<ApiResponse<Map<String, String>>>() {
                            @Override
                            public void onResponse(Call<ApiResponse<Map<String, String>>> call, Response<ApiResponse<Map<String, String>>> response) {
                                if (response.isSuccessful()) {
                                    ApiResponse<Map<String, String>> apiResponse = response.body();
                                    if (Objects.nonNull(apiResponse) && Objects.equals(apiResponse.getCode(), 200)) {
                                        // 模拟登录成功
                                        Map<String, String> data = apiResponse.getData();
                                        Log.d(TAG, "onResponse: " + data);
                                        String token = data.get("token");
                                        SPUtils spUtils = new SPUtils(requireContext());
                                        spUtils.putString("token", token);
                                        spUtils.putBoolean("hasLogin", true);
                                        Intent intent = new Intent(requireContext(), MainActivity.class);
                                        startActivity(intent);
                                        ToastUtils.show(requireContext(), "登录成功");
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Call<ApiResponse<Map<String, String>>> call, Throwable t) {
                                SnackBarUtil.showSnackBar(requireActivity(), root, "网络错误" + t.getMessage(), true, 0, null);
                            }
                        });
            }
        } else {
            SnackBarUtil.showSnackBar(requireActivity(), view, "请先阅读并同意《用户协议》《隐私协议》", true, 0, null);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}